package com.buba.system.controller;

import com.buba.system.pojo.UserInfo;
import com.buba.system.service.UserService;
import com.buba.system.service.impl.UserServiceImpl;
import com.buba.util.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/upFileServlet")
@MultipartConfig
public class upFileServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();
    @Override
    public void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        System.out.println("更改头像");
        //获取上传的文件
        Part upFile = request.getPart("upFile");
        //设置上传文件保存的位置
        //需要获取当前项目的路径  realPath指向webapp/images 目录下
        String realPath = request.getServletContext().getRealPath("/images/");
        File file = new File(realPath);
        if (!file.exists())file.mkdirs();
        //获取文件名 webapp/images/123.jpg
        String submittedFileName = upFile.getSubmittedFileName();
        // 保存上传文件
        upFile.write(realPath + submittedFileName);
        //将头像路径保存到数据库用户表中 参数： 登录用户id , 头像存在的路径
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("login");
        userService.updHeadImg(userInfo.getUserId(), "images/" + submittedFileName);
        // 修改会话域中的登录用户
        userInfo.setHeadImg("images/"+ submittedFileName);
        request.getSession().setAttribute("login",userInfo);
        response.sendRedirect("buba/system/basic.html");
    }
}
